package com.bbx.taxi.client.Activity.Address;

import android.animation.LayoutTransition;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapStatusChangeListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.bbx.androidapi.util.ToastUtil;
import com.bbx.api.sdk.model.passanger.LeadStopsGetNearbysBuild;
import com.bbx.api.sdk.model.passanger.Return.GetNearbysPoints;
import com.bbx.api.sdk.model.passanger.Return.LeadStopsGetNearbys;
import com.bbx.api.util.LogUtils;
import com.bbx.taxi.client.Activity.Base.BaseMapBBXActivity;
import com.bbx.taxi.client.Activity.Main.MainPresenter;
import com.bbx.taxi.client.Adapter.EditAddressAdapter;
import com.bbx.taxi.client.Bean.Attribute.MainAttribute;
import com.bbx.taxi.client.Bean.City;
import com.bbx.taxi.client.Bean.Extra.AddressMsg;
import com.bbx.taxi.client.Bean.Line.CitiesBean.AppCitysBean;
import com.bbx.taxi.client.Bean.Value;
import com.bbx.taxi.client.DB.AddressDB;
import com.bbx.taxi.client.DB.LineDB;
import com.bbx.taxi.client.DB.Util.DBcolumns;
import com.bbx.taxi.client.MyApplication.OnLocationResultListener;
import com.bbx.taxi.client.R;
import com.bbx.taxi.client.Task.LeadStopsGetNearbysTask;
import com.bbx.taxi.client.Task.LeadStopsGetNearbysTask.Back;
import com.bbx.taxi.client.Util.DateFormat;
import com.bbx.taxi.client.Util.IsDataFail;
import com.bbx.taxi.client.Util.ToCity2;
import com.bbx.taxi.client.widget.Dailog.MyAlertDailog;
import com.bbx.taxi.client.widget.Dailog.MyAlertDailog.onClickSingleListener;
import com.bbx.taxi.client.widget.Drag.CityDragLayout;
import com.bbx.taxi.client.widget.Drag.CityDragLayout.OnCityDragViewStatusListener;
import com.yanxuwen.loadview.LoadingDialog;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;

/**
 * 编辑地址，定位地址
 */
public class EditAddressActivity extends BaseMapBBXActivity implements
OnClickListener, OnItemClickListener, OnGetPoiSearchResultListener,
OnGetGeoCoderResultListener, TextWatcher, OnLocationResultListener,
OnCityDragViewStatusListener ,DBcolumns{
	@Bind(R.id.layout_nodata)
	LinearLayout layout_nodata;
	@Bind(R.id.layout_city_search)
	RelativeLayout layout_city_search;
	@Bind(R.id.et_city)
	EditText et_city;
	@Bind(R.id.listview)
	ListView listview;
	@Bind(R.id.et_edit)
	EditText et_edit;
	@Bind(R.id.layout_city)
	LinearLayout layout_city;
	@Bind(R.id.tv_city)
	TextView tv_city;
	@Bind(R.id.tv_city_jiantou)
	ImageView tv_city_jiantou;
	@Bind(R.id.tv_loading)
	TextView tv_loading;
	@Bind(R.id.bmapView)
	MapView mMapView;
	@Bind(R.id.iv_delete)
	ImageView iv_delete;
	@Bind(R.id.iv_city_delete)
	ImageView iv_city_delete;
	@Bind(R.id.tv_myposition)
	TextView tv_myposition;
	@Bind(R.id.icon_mapid)
	ImageView icon_mapid;
	/** 切换城市提示 */
	@Bind(R.id.layout_switch_city)
	LinearLayout layout_switch_city;
	@Bind(R.id.iv_locate)
	ImageView iv_locate;
	@Bind(R.id.citydragLayout)
	public CityDragLayout citydragLayout;
	@Bind(R.id.layout_map)
	RelativeLayout layout_map;
	@Bind(R.id.map_view)
	View map_view;
	@Bind(R.id.layout_listview)
	LinearLayout layout_listview;
	@Bind(R.id.tv_cancel)
	TextView tv_cancel;
	MainAttribute main;
	public final static int TYPE_GEOCODER = 0;
	public final static int TYPE_SEARCH = 1;
	public final static int TYPE_COLLECT = 3;
	public int type = TYPE_GEOCODER;
	public final static int MSG_SELETE_CITY = 0;
	private BaiduMap mBaiduMap;
	boolean isFirstLoc = true;// 是否首次定位
	public LocationClient mLocClient;
	private PoiSearch mPoiSearch = null;
	private GeoCoder mSearch = null; // 地理编码
	private ReverseGeoCodeResult myposition;// 我的位置
	/** 搜索结果列表 */
	private List<PoiInfo> list_key;
	/** 地理编码列表 */
	private List<PoiInfo> list_geo;
	/** 收藏地址跟历史地址 */
	private List<Map<String, String>> list_collect;
	List<City> cityList = new ArrayList<City>();
	private EditAddressAdapter mMyAdapter_geocoder;// 地面编码
	private EditAddressAdapter mMyAdapter_search;// 搜索结果
	private EditAddressAdapter mMyAdapter_collect;// 收藏跟历史
	private double latitude;
	private double longitude;
	private AddressDB db_address;
	private int intentType;
	private int viewid;
	private boolean isInCity = false;// 判断是否是市内用车
	private boolean isStart=true;//判断是出发地还是目的地
	private boolean isInKJ = false;// 判断是否是快件
	private boolean isOpend = false;// 是否有开通
	private String defaultcity="";
	private LineDB db_line;// 线路数据库
	private LoadingDialog dialog;
	/** 判断是否设置定位城市 */
	private boolean isLocationCity = true;
	private String is_detail = Value.CITY_NODETAIL;
	/** 传递到Handler用的分隔符 */
	private String split = "%#";
	private String address_name;
	private Intent intent;
	List<AppCitysBean> list_satrtcity;
	/**推荐上车点*/
	private List<Marker> list_tuijian_marker=new ArrayList<Marker>();
	private View tuijian_view; 
	private TextView tuijian_info; 
	private View v_offset;//覆盖物的偏移量
	BitmapDescriptor bdtuijian = BitmapDescriptorFactory
			.fromResource(R.drawable.icon_tuijian);
	
	protected void onCreate(Bundle savedInstanceState) {
		showTitle(false);
		setContentView(R.layout.editaddress);
		super.onCreate(savedInstanceState);
		setOnCloseSwipeLayout(false);
	}


	@Override
	protected void initView() {
		main= MainAttribute.getInstance();
		tv_city.addTextChangedListener(new cityTextWatcher());
		LayoutInflater inflater=LayoutInflater.from(context);
		tuijian_view=(View)inflater.inflate(R.layout.marker_tuijian,null);
		tuijian_info=(TextView)tuijian_view.findViewById(R.id.tv_info);
//		v_offset=(View)tuijian_view.findViewById(R.id.v_offset);
				
		layout_base.setBackgroundColor(getResources().getColor(R.color.white));
		citydragLayout.setOnCityDragViewStatusListener(this);
		//      listview.setEmptyView(layout_nodata);
		//      setTitle(getString(R.string.edit_address));
		intent = getIntent();
		viewid=intent.getExtras().getInt(AddressMsg.extra_viewid);
		isInCity = viewid==Value.VIEWID_SN;
		isInKJ = viewid==Value.VIEWID_KJ;
		isOpend = intent.getExtras().getBoolean(AddressMsg.extra_cityopend);
		defaultcity=intent.getExtras().getString(AddressMsg.extra_city);
		loaddialog=new LoadingDialog(this, Value.LOADDIALOGTIME);
		db_line = new LineDB();
		db_address = new AddressDB();
		list_key = new ArrayList<PoiInfo>();
		list_geo = new ArrayList<PoiInfo>();
		list_collect = new ArrayList<Map<String, String>>();
		mMyAdapter_geocoder = new EditAddressAdapter(this, list_geo,
				EditAddressAdapter.TYPE_GEOCODER);
		mMyAdapter_search = new EditAddressAdapter(this, list_key,
				EditAddressAdapter.TYPE_SEARCH);
		mMyAdapter_collect = new EditAddressAdapter(this, list_collect,
				EditAddressAdapter.TYPE_COLLECT, db_address);
		listview.setAdapter(mMyAdapter_geocoder);
		listview.setOnItemClickListener(this);
		tv_myposition.setOnClickListener(this);
		layout_city.setOnClickListener(this);
		tv_cancel.setOnClickListener(this);
		et_edit.addTextChangedListener(this);
		et_edit.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus&&layout_city.getVisibility()!=View.GONE) {
					if (tv_city.getText().toString() != null
							&& !tv_city.getText().toString().equals("")
							&& !tv_city.getText().toString()
							.equals(getString(R.string.default_city))
							&& !tv_city.getText().toString().equals("null")) {
						hideCity();
					} else {
						setEditTextCityFocusable();
						if(!isInCity){
							ToastUtil.showToast(context, R.string.choice_city);
						}
					}
				}
			}
		});
		iv_delete.setOnClickListener(this);
		iv_city_delete.setOnClickListener(this);
		et_edit.setOnClickListener(this);
		iv_locate.setOnClickListener(this);
		mPoiSearch = PoiSearch.newInstance();
		mPoiSearch.setOnGetPoiSearchResultListener(this);
		// 初始化搜索模块，注册事件监听
		mSearch = GeoCoder.newInstance();
		mSearch.setOnGetGeoCodeResultListener(this);
		intentType = intent.getExtras().getInt(AddressMsg.extra_editaddress);
		switch (intentType) {
		case AddressMsg.ADDRESS_START_MAIN:
		case AddressMsg.ADDRESS_START_CHANGE:
			isStart=true;
			setCityList();
			et_edit.setFocusable(false);
			// 设置hint
			if (isInKJ) {
				// tv_edit.setHint(R.string.hint_start_kj);
				et_edit.setHint(R.string.hint_start_kj);
			} else {
				// tv_edit.setHint(R.string.hint_start);
				et_edit.setHint(R.string.hint_start);
			}
			//			setTitle(getString(R.string.start_address));
			address_name = "";
			setDefaultCity(true);

			if (isInCity &&isStart) {
				tv_city_jiantou.setVisibility(View.GONE);
			}
			// 定位失败，则不显示地图
			if (isNoCity()||!isOpend||isInCity) {
				type=TYPE_COLLECT;
				showEditText(false);
				if(isInCity){
					hideCity();
				}else{
					showCity();
					
				}
			
			}else{
//				type=TYPE_GEOCODER;
//				hideEditText();
//				hideCity();
//				et_edit.setFocusable(false);
//				et_city.setFocusable(false);
//				hideInput();
				type=TYPE_COLLECT;
				showEditText(false);
				if(defaultcity==null||defaultcity.equals("")){
					showCity();
				}else{
					hideCity();
				}

				
				mApplication.setOnLocationResultListener(this);
				latitude = mApplication.latitude;
				longitude = mApplication.longitude;
				initmap();
				if (latitude != 0 && longitude != 0) {
					onGeoCoder(latitude, longitude);
				}
			}


			break;
		case AddressMsg.ADDRESS_END_MAIN:
			isStart=false;
			setCityList();
			type=TYPE_COLLECT;
			setDefaultCity(false);
			showEditText(false);
			// 设置hint
			if (isInKJ) {
				// tv_edit.setHint(R.string.hint_end_kj);
				et_edit.setHint(R.string.hint_end_kj);
			} else {
				// tv_edit.setHint(R.string.hint_end);
				et_edit.setHint(R.string.hint_end);
			}
			//			setTitle(getString(R.string.end_address));
			if (main.getStartCity(isInCity).equals("")) {
				address_name = "";
			} else {
				address_name = main.getStartCity(isInCity);
			}
			//默认是打开城市列表
			if (mApplication.loctionCity == null
					|| mApplication.loctionCity.equals("")
					|| mApplication.loctionCity.equals("null")) {
				showCity();
			} else {
				if((defaultcity==null||defaultcity.equals(""))&&!isInCity){
					showCity();
				}else{
					hideCity();
				}

			}
			break;
		case AddressMsg.ADDRESS_COLLECT:
			showEditText(false);
			break;
		}
	}

	@Override
	protected void initData() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void desotryItems() {

	}

	public void initmap() {
		mMapView.setVisibility(View.VISIBLE);
		icon_mapid.setVisibility(View.VISIBLE);
		iv_locate.setVisibility(View.VISIBLE);
		// 如果不是出发地，则不定位
		if (intentType != AddressMsg.ADDRESS_START_MAIN
				&& intentType != AddressMsg.ADDRESS_START_CHANGE) {
			return;
		}
		mBaiduMap = mMapView.getMap();
		MapStatusUpdate u = MapStatusUpdateFactory.zoomTo(16);
		mBaiduMap.animateMapStatus(u);
		if (mBaiduMap != null) {
			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					mBaiduMap
					.setMyLocationConfigeration(new MyLocationConfiguration(
							LocationMode.NORMAL,
							true,
							BitmapDescriptorFactory
							.fromResource(R.drawable.icon_mapid2)));
				}
			}, 100);
			mBaiduMap.setMyLocationEnabled(true);
			mBaiduMap
			.setOnMapStatusChangeListener(new OnMapStatusChangeListener() {//

				@Override
				public void onMapStatusChangeStart(MapStatus mapStatus) {
					tv_myposition
					.setText(getString(R.string.my_location));
					tv_myposition.setVisibility(View.GONE);
					myposition = null;

				}

				@Override
				public void onMapStatusChangeFinish(MapStatus mapStatus) {
					tv_loading.setVisibility(View.VISIBLE);
					tv_loading.setText(getString(R.string.tv_loading));
					onGeoCoder(mapStatus.target.latitude,
							mapStatus.target.longitude);
				}

				@Override
				public void onMapStatusChange(MapStatus mapStatus) {
					// TODO Auto-generated method stub

				}
			});
		}

	}

	/**
	 * 读取所有数据
	 */
	public void readAllDB_address() {
		if (list_collect != null)
			list_collect.clear();
		readAllDB_collect(Value.ADDRESS_TYPE_COLLECTE, tv_city.getText()
				.toString());
	}

	/**
	 * 读取所有数据,先收藏后历史
	 */
	public void readAllDB_collect(final String isCollection, final String cityname) {
		new AsyncTask<Void, Void, Void>(){

			@Override
			protected Void doInBackground(Void... arg0) {
				list_collect.addAll(db_address.readAllDB(context, isCollection, cityname));
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				if (isCollection.equals(Value.ADDRESS_TYPE_COLLECTE)) {
					readAllDB_collect(Value.ADDRESS_TYPE_HISTORY, cityname);
				}
				if(type==TYPE_COLLECT){
					notifyDataSetChanged(mMyAdapter_collect);
				}
				super.onPostExecute(result);
			}
		    	
		}.execute();
		
	
	}

	/**
	 * 地理编码搜索
	 */
	public void onGeoCoder(double latitude, double longitude) {
		if(type == TYPE_GEOCODER){
			LatLng ptCenter = new LatLng(latitude, longitude);
			// 反Geo搜索
			mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(ptCenter));
		}
	}

	/**
	 * 城市关键字搜索,search==true的时候无论是否有值，都要搜索【用于具体信息，如厦门北站这类信息】，false的时候，则根据有值才搜索
	 */
	public void onCityKeySearch(String key,boolean search) {
		if((key!=null&&!key.equals(""))||search){
			PoiCitySearchOption info = new PoiCitySearchOption();
			info.city(tv_city.getText().toString());
			info.pageCapacity(50);
			String cutcity=ToCity2.getCityName(tv_city.getText().toString());
			LogUtils.e("",tv_city.getText().toString() +cutcity+ key+"");
			info.keyword(tv_city.getText().toString() +cutcity+ key);
			mPoiSearch.searchInCity(info);
		}
	}

	public void initDefaultLocation(BDLocation location) {

		if (location != null) {// 先默认定位
			MyLocationData locData = new MyLocationData.Builder()
					.accuracy(location.getRadius())
					// 此处设置开发者获取到的方向信息，顺时针0-360
					.direction(100).latitude(location.getLatitude())
					.longitude(location.getLongitude()).build();
			mBaiduMap.setMyLocationData(locData);
			if (isFirstLoc) {
				isFirstLoc = false;
				LatLng ll = new LatLng(location.getLatitude(),
						location.getLongitude());
				MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
				mBaiduMap.animateMapStatus(u);
			}
		}
	}

	public void initDefaultLocation(ReverseGeoCodeResult result) {
		//
		// if (result != null) {// 先默认定位
		// MyLocationData locData = new MyLocationData.Builder()
		// .accuracy(result.getAddressDetail()..getRadius())
		// // 此处设置开发者获取到的方向信息，顺时针0-360
		// .direction(100).latitude(location.getLatitude())
		// .longitude(location.getLongitude()).build();
		// mBaiduMap.setMyLocationData(locData);
		// if (isFirstLoc) {
		// isFirstLoc = false;
		// LatLng ll = new LatLng(location.getLatitude(),
		// location.getLongitude());
		// MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
		// mBaiduMap.animateMapStatus(u);
		// }
		// }
	}

	@Override
	protected void onPause() {
		super.onPause();
		// activity 暂停时同时暂停地图控件
		mMapView.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
		// activity 恢复时同时恢复地图控件
		mMapView.onResume();
	}

	@Override
	protected void onDestroy() {
		mApplication.removeOnLocationResultListener(this);

		super.onDestroy();
		// activity 销毁时同时销毁地图控件
		// mMapView.onDestroy();
	}

	/**
	 * 搜索结果
	 */
	public void onGetPoiDetailResult(PoiDetailResult arg0) {
	}

	@Override
	public void onGetPoiResult(PoiResult result) {
		if (result == null
				|| result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND
				|| result.getAllPoi() == null) {
			list_key.clear();
			notifyDataSetChanged(mMyAdapter_search);
			return;
		} else {
			list_key.clear();
			tv_loading.setText(getString(R.string.tv_loading));
			listview.setVisibility(View.VISIBLE);
			List<PoiInfo> listpoi = result.getAllPoi();
			for(int i=listpoi.size()-1;i>=0;i--){
				if(listpoi.get(i).location==null)
					listpoi.remove(i);
			}
			if (is_detail.equals(Value.CITY_DETAIL)) {// 显示具体信息，则值显示一个
				list_key.add(listpoi.get(0));
			} else {
				list_key.addAll(listpoi);
			}

			notifyDataSetChanged(mMyAdapter_search);
		}

	}

	/**
	 * 地理编码结果（地理到经纬度的结果）
	 */
	public void onGetGeoCodeResult(GeoCodeResult result) {
		if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
			list_geo.clear();
			notifyDataSetChanged(mMyAdapter_geocoder);
			return;
		}

	}

	/**
	 * 地理编码结果（经纬度到地址的结果）
	 */
	public void onGetReverseGeoCodeResult(final ReverseGeoCodeResult result) {

	}

	@Override
	public void afterTextChanged(Editable s) {
		if (!s.toString().isEmpty()) {
			if (isNoCity()) {
				if (isInCity &&isStart) {

				} else {
					showCity();
				}
			} else {
				notifyDataSetChanged(mMyAdapter_search);
				iv_delete.setVisibility(View.VISIBLE);
				tv_loading.setVisibility(View.VISIBLE);
				tv_loading.setText(getString(R.string.tv_loading));
			}

		} else {
			iv_delete.setVisibility(View.GONE);
			if(type!=TYPE_GEOCODER){
				notifyDataSetChanged(mMyAdapter_collect);
			}else{
				notifyDataSetChanged(mMyAdapter_geocoder);
			}
		}
		onCityKeySearch(s.toString(),false);

	}

	@Override
	public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
			int arg3) {

	}

	@Override
	public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_cancel:
		case R.id.iv_left:
			// if (layout_search.getVisibility() == View.VISIBLE) {
			// if (intentType == AddressMsg.ADDRESS_START)
			// hideEditText();
			// else
			// onfinish();
			// } else {
			// onfinish();
			// }
			onfinish();
			break;
		case R.id.layout_city:
			if (isInCity &&intentType==AddressMsg.ADDRESS_START_MAIN) {

			} else {
				if (type != TYPE_SEARCH) {
					showEditText(false);
					showCity();
				} else {
					showCity();
				}
			}

			break;
			// case R.id.tv_edit:
			// showEditText(true);
			// break;
		case R.id.iv_delete:
			et_edit.setText("");
			break;
		case R.id.iv_city_delete:
			et_city.setText("");
			break;
		case R.id.tv_myposition:
//			if (myposition != null) {
//
//				new AsyncTask<Void, Void, Void>() {
//					String city;
//					String name="";
//					@Override
//					protected Void doInBackground(Void... params) {
//						city=myposition.getAddressDetail().district.trim();
//						//判断是二级城市
//						if(ToCity.isDistrictExist(mApplication,city,isInCity)){
//							city=myposition.getAddressDetail().district.trim();
//							name=city+ " "+myposition.getAddress();
//							name=name.replace(myposition.getAddressDetail().province+ myposition.getAddressDetail().city+city, "");
//						}else{
//							city=myposition.getAddressDetail().city.trim();
//							name=city+ " "+myposition.getAddress();
//							name=name.replace(myposition.getAddressDetail().province+city, "");
//						}
//						return null;
//					}
//
//					@Override
//					protected void onPostExecute(Void result) {
//						Bundle bundle = new Bundle();
//						bundle.putString(AddressMsg.extra_address_name,name);
//						// 我的位置，则按照百度地图给的城市
//						bundle.putString(AddressMsg.extra_address_city,
//								city);
//						bundle.putString(AddressMsg.extra_address_address,
//								myposition.getAddress());
//						bundle.putDouble(AddressMsg.extra_address_latitude,
//								myposition.getLocation().latitude);
//						bundle.putDouble(AddressMsg.extra_address_longitude,
//								myposition.getLocation().longitude);
//						setRecommend( bundle,0);
//						super.onPostExecute(result);
//					}
//
//				}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
//
//			}
			break;
		case R.id.et_edit:
			if (tv_city.getText().toString() != null
			&& !tv_city.getText().toString().equals("")
			&& !tv_city.getText().toString()
			.equals(getString(R.string.default_city))
			&& !tv_city.getText().toString().equals("null")) {
				hideCity();
				showEditText(true);
			} else {
				setEditTextCityFocusable();
				ToastUtil.showToast(context, R.string.choice_city);
			}


			break;
		case R.id.iv_locate:
			setCenterPoint(mApplication.latitude, mApplication.longitude, 16);
			break;
		default:
			super.onClick(v);
			break;
		}

	}

	/**
	 * 判断是否是具体信息搜索，如厦门北站
	 */
	public void onIsSearchDetail(String is_detail, String city) {
		tv_city.setText(city);
		// 具体信息，如厦门北站
		if (is_detail != null && is_detail.equals(Value.CITY_DETAIL)) {
			et_edit.setText(et_edit.getText().toString());
			et_edit.setSelection(et_edit.getText().length());
			et_edit.setHint(city);
			et_edit.setEnabled(false);
			onCityKeySearch("",true);
			iv_delete.setVisibility(View.VISIBLE);
			tv_loading.setVisibility(View.VISIBLE);
			tv_loading.setText(getString(R.string.tv_loading));
			iv_delete.setVisibility(View.GONE);
			hideInput();
		} else {
			showInput();
			et_edit.setEnabled(true);
			et_edit.setHint(getResources().getString(R.string.hint_end));
			iv_delete.setVisibility(View.GONE);
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {

		if (arg0.getAdapter() == mMyAdapter_geocoder) {
			Bundle bundle = new Bundle();
			String name = list_geo.get(position).name;
			String city =tv_city.getText().toString();
			if (ToCity2.isCityDetail(name, name,isStart,isInCity)) {
				bundle.putString(AddressMsg.extra_address_name, name);
				// 地理编码信息，则按照百度地图给的城市
				bundle.putString(AddressMsg.extra_address_city, name);
			} else {
				bundle.putString(AddressMsg.extra_address_name, city + " "
						+ name);
				// 地理编码信息，则按照百度地图给的城市
				bundle.putString(AddressMsg.extra_address_city, city);
			}

			bundle.putString(AddressMsg.extra_address_address,
					list_geo.get(position).address);
			bundle.putDouble(AddressMsg.extra_address_latitude,
					list_geo.get(position).location.latitude);
			bundle.putDouble(AddressMsg.extra_address_longitude,
					list_geo.get(position).location.longitude);
			if(mMyAdapter_geocoder.isRecommend()){//列表全是推荐上车点
				bundle.putBoolean(AddressMsg.extra_address_isRecommend, mMyAdapter_geocoder.isRecommend());
			}else{///列表中含推荐上车点
				if(list_geo.get(position).uid!=null&&list_geo.get(position).uid.equals("zzbbx1008611bbxzz")){
					bundle.putBoolean(AddressMsg.extra_address_isRecommend, mMyAdapter_geocoder.isHasRecommend());
				}else{
					bundle.putBoolean(AddressMsg.extra_address_isRecommend, mMyAdapter_geocoder.isRecommend());
				}
				
			}
			/*	Intent intent = new Intent();
			intent.putExtras(bundle);
			setResult(resultCode, intent);
			onfinish();*/
			if(mMyAdapter_geocoder.isRecommend()||isInCity||mMyAdapter_geocoder.isHasRecommend()){
				//已经检索过站点列表
				Intent intent = new Intent();
				intent.putExtras(bundle);
				setResult(resultCode, intent);
				onfinish();
			}else{

				setRecommend( bundle,0);
			}
		} else if (arg0.getAdapter() == mMyAdapter_search) {
			Bundle bundle = new Bundle();
			// bundle.putString(AddressMsg.extra_address_name,
			// list_key.get(position).city + " "
			// + list_key.get(position).name);
			// 搜索去城市，则取左上角的城市名
			// bundle.putString(AddressMsg.extra_address_city,
			// list_key.get(position).city);
			String name = list_key.get(position).name;
			String city = list_key.get(position).city;
			if (ToCity2.isCityDetail(name, name,isStart,isInCity)) {
				bundle.putString(AddressMsg.extra_address_name, name);
				// 地理编码信息，则按照百度地图给的城市
				bundle.putString(AddressMsg.extra_address_city, name);
			} else {

				if (is_detail.equals(Value.CITY_DETAIL)) {// 显示具体信息，则值显示一个
					bundle.putString(AddressMsg.extra_address_name, tv_city
							.getText().toString());
					bundle.putString(AddressMsg.extra_address_city, tv_city
							.getText().toString());
				} else {
					bundle.putString(
							AddressMsg.extra_address_name,
							tv_city.getText().toString() + " "
									+ list_key.get(position).name);
					bundle.putString(AddressMsg.extra_address_city, tv_city
							.getText().toString());
				}
			}

			bundle.putString(AddressMsg.extra_address_address,
					list_key.get(position).address);
			bundle.putDouble(AddressMsg.extra_address_latitude,
					list_key.get(position).location.latitude);
			bundle.putDouble(AddressMsg.extra_address_longitude,
					list_key.get(position).location.longitude);
			bundle.putBoolean(AddressMsg.extra_address_isRecommend, mMyAdapter_search.isRecommend());
			/*Intent intent = new Intent();
			intent.putExtras(bundle);
			setResult(resultCode, intent);
			onfinish();*/
			if(mMyAdapter_search.isRecommend()||isInCity){
				//已经检索过站点列表
				Intent intent = new Intent();
				intent.putExtras(bundle);
				setResult(resultCode, intent);
				onfinish();
			}else{
				setRecommend(bundle,1);
			}

		} else if (arg0.getAdapter() == mMyAdapter_collect) {
			Bundle bundle = new Bundle();
			bundle.putString(AddressMsg.extra_address_name,
					list_collect.get(position).get(DBcolumns.ADDRESS_NAME));
			// 历史记录城市则取数据库，没有则取空
			bundle.putString(AddressMsg.extra_address_city,
					list_collect.get(position).get(DBcolumns.ADDRESS_CITY));
			bundle.putString(AddressMsg.extra_address_address, list_collect
					.get(position).get(DBcolumns.ADDRESS_ADDRESS));
			bundle.putDouble(
					AddressMsg.extra_address_latitude,
					Double.parseDouble(list_collect.get(position).get(
							DBcolumns.ADDRESS_LATITUDE)));
			bundle.putDouble(
					AddressMsg.extra_address_longitude,
					Double.parseDouble(list_collect.get(position).get(
							DBcolumns.ADDRESS_LONGITUDE)));
			bundle.putBoolean(AddressMsg.extra_address_isRecommend, mMyAdapter_collect.isRecommend());
			/*Intent intent = new Intent();
			intent.putExtras(bundle);
			setResult(resultCode, intent);
			onfinish();*/
			if(mMyAdapter_collect.isRecommend()||isInCity){
				String name="";
				if(isInCity){
					name=bundle.getString(AddressMsg.extra_address_name);
				}else{
					name=bundle.getString(AddressMsg.extra_address_city)+" "+
							bundle.getString(AddressMsg.extra_address_name);
				}
				bundle.putString(AddressMsg.extra_address_name,name);
				//已经检索过站点列表
				Intent intent = new Intent();
				intent.putExtras(bundle);
				setResult(resultCode, intent);
				onfinish();
			}else{
				setRecommend(bundle,2);
			}
		}
	}
	public  boolean isNull(Double s) {
		if (s != null && s != 0)
			return true;
		return false;
	}
	/**
	 * 检索推荐站点
	 * tag 标记是哪类适配器
	 * */
	public void setRecommend(final Bundle bundle,final int tag){
		if(isNull(bundle.getDouble(AddressMsg.extra_address_longitude, 0.0))
				&&isNull(bundle.getDouble(AddressMsg.extra_address_latitude, 0.0))){
			LeadStopsGetNearbysBuild build=new LeadStopsGetNearbysBuild(this);
			build.lat=bundle.getDouble(AddressMsg.extra_address_latitude, 0.0)+"";
			build.lng=bundle.getDouble(AddressMsg.extra_address_longitude, 0.0)+"";
    		build.time=DateFormat.onDate_Long(main.getTime(isInCity))/ 1000;
			new LeadStopsGetNearbysTask(this, build, true, new Back() {

				@SuppressWarnings("unchecked")
				@Override
				public void success(Object object) {
					if(object!=null &&object instanceof LeadStopsGetNearbys ){
						LeadStopsGetNearbys mNearbys=(LeadStopsGetNearbys) object;
						if(mNearbys!=null&&mNearbys.points!=null&&!mNearbys.points.isEmpty()){
							Collections.sort(mNearbys.points,MainPresenter.mComparator);
							/*for(GetNearbysPoints m:mNearbys.points){
								Log.e("lbb", "------GetNearbysPoints1-----"+m.dis);
							}*/
							boolean isExclusive=false;
    						for(GetNearbysPoints mGetPoint:mNearbys.points){
    							if(mGetPoint.exclusive==1){//互斥
    								 isExclusive=true;
    								 break;
    							}
    						}
							if(isExclusive){

								if(mNearbys.points.size()==1){
									bundle.putString(AddressMsg.extra_address_name,bundle.getString(AddressMsg.extra_address_city)+" "+mNearbys.points.get(0).da_name);
									bundle.putString(AddressMsg.extra_address_city,bundle.getString(AddressMsg.extra_address_city));
									bundle.putString(AddressMsg.extra_address_address,mNearbys.points.get(0).da_address);
									if(mNearbys.points.get(0).da_point!=null&&!mNearbys.points.get(0).da_point.isEmpty()){
										if(mNearbys.points.get(0).da_point.size()>1){
											bundle.putDouble(AddressMsg.extra_address_latitude,mNearbys.points.get(0).da_point.get(1));
										}
										bundle.putDouble(AddressMsg.extra_address_longitude,mNearbys.points.get(0).da_point.get(0));
									}
									bundle.putBoolean(AddressMsg.extra_address_isRecommend,true);
									Intent intent = new Intent();
									intent.putExtras(bundle);
									setResult(resultCode, intent);
									onfinish();
								}else{
									final MyAlertDailog dialog = new MyAlertDailog(EditAddressActivity.this);

									dialog.setTitle("温馨提示");
									dialog.setContent("为方便您的及时、快捷出行，请选择附近的推荐站点乘车");
									dialog.setSingle(getString(R.string.mydailog_confirm));
									dialog.show();
									dialog.setOnClickSingleListener(new onClickSingleListener() {
										@Override
										public void onClickSingle() {
											dialog.dismiss();
										}
									});
									//刷新列表
									if(tag==2){//mMyAdapter_collect
										List<Map<String, String>> listcollect= new ArrayList<Map<String, String>>();
										Map<String, String> map=null;
										for(GetNearbysPoints mPoint:mNearbys.points){
											if(mPoint!=null){
												map=new HashMap<String, String>();
												map.put(ADDRESS_NAME, mPoint.da_name);
												map.put(ADDRESS_CITY, bundle.getString(AddressMsg.extra_address_city));
												map.put(ADDRESS_ADDRESS, mPoint.da_address);
												if(mPoint.da_point!=null&&!mPoint.da_point.isEmpty()){
													if(mPoint.da_point.size()>1){
														map.put(ADDRESS_LATITUDE, mPoint.da_point.get(1)+"");
													}
													map.put(ADDRESS_LONGITUDE, mPoint.da_point.get(0)+"");
												}
												map.put(ADDRESS_COLLECTION, "0");
												listcollect.add(map);
											}
										}
										if(!listcollect.isEmpty()){
											list_collect.clear();
											list_collect.addAll(listcollect);

											onisShowNodata(mMyAdapter_collect,true);
											tv_loading.setVisibility(View.GONE);
										}

									}else{
										List<PoiInfo> listpoi=new ArrayList<PoiInfo>(); 
										PoiInfo poiinfo=null;
										for(GetNearbysPoints mPoint:mNearbys.points){
											if(mPoint!=null){
												poiinfo = new PoiInfo();
												poiinfo.name=mPoint.da_name;
												poiinfo.address =mPoint.da_address;
												poiinfo.city =bundle.getString(AddressMsg.extra_address_city);
												if(mPoint.da_point!=null&&!mPoint.da_point.isEmpty()){
													LatLng mLatLng=null;//new LatLng(lat, lng);
													if(mPoint.da_point.size()>1){
														mLatLng=new LatLng(mPoint.da_point.get(1), mPoint.da_point.get(0));
													}else{
														mLatLng=new LatLng(0.0, mPoint.da_point.get(0));
													}
													poiinfo.location = mLatLng;
												}
												listpoi.add(poiinfo);
											}
										}
										if(tag==0){//mMyAdapter_geocoder
											if(!listpoi.isEmpty()){
												list_geo.clear();
												list_geo.addAll(listpoi);

												onisShowNodata(mMyAdapter_geocoder,true);
												tv_loading.setVisibility(View.GONE);
											}
										}else if(tag==1){//mMyAdapter_search
											if(!listpoi.isEmpty()){
												list_key.clear();
												list_key.addAll(listpoi);

												onisShowNodata(mMyAdapter_search,true);
												tv_loading.setVisibility(View.GONE);
											}
										}
									}
								}
							}else{
								Intent intent = new Intent();
								intent.putExtras(bundle);
								setResult(resultCode, intent);
								onfinish();

							}

						}else{
							Intent intent = new Intent();
							intent.putExtras(bundle);
							setResult(resultCode, intent);
							onfinish();

						}
					}else{
						Intent intent = new Intent();
						intent.putExtras(bundle);
						setResult(resultCode, intent);
						onfinish();
					}
				}
				@Override
				public void fail(int status, String msg) {
					Intent intent = new Intent();
					intent.putExtras(bundle);
					setResult(resultCode, intent);
					onfinish();
				}
			}).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

		}else{
			Intent intent = new Intent();
			intent.putExtras(bundle);
			setResult(resultCode, intent);
			onfinish();
		}
	}
	@Override
	public void onLocationResult(BDLocation location) {
		latitude = location.getLatitude();
		longitude = location.getLongitude();
		initDefaultLocation(location);
		onGeoCoder(latitude, longitude);
		// 只定位一次
		mApplication.removeOnLocationResultListener(this);
		String city = location.getCity();
		if (city != null && isLocationCity) {
		}
	}

	@Override
	public void onLocationResult(ReverseGeoCodeResult result) {
		latitude = result.getLocation().latitude;
		longitude = result.getLocation().longitude;
		initDefaultLocation(result);
		onGeoCoder(latitude, longitude);
		// 只定位一次
		mApplication.removeOnLocationResultListener(this);
		String city = result.getAddressDetail().city;
		if (city != null && isLocationCity) {
		}
	}

	@Override
	public void onLocationFail(boolean isnet) {
		// TODO Auto-generated method stub

	}

	public void showEditText(final boolean isInput) {
		int time=0;
		if (intentType == AddressMsg.ADDRESS_START_MAIN) {
			LayoutTransition lt = new LayoutTransition();
			lt.disableTransitionType(LayoutTransition.DISAPPEARING);
			layout_listview.setLayoutTransition(lt);
			time=800;
		}
		map_view.setVisibility(View.GONE);
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				if (et_edit.getText().toString().equals("")) {
					notifyDataSetChanged(mMyAdapter_collect);
				} else {
					notifyDataSetChanged(mMyAdapter_search);
				}
				// tv_edit.setVisibility(View.GONE);
				et_edit.setFocusable(true);
				if (isInput) {
					InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
				}
			}
		}, time);
	}

	public void hideEditText() {
		map_view.setVisibility(View.VISIBLE);
		// tv_edit.setVisibility(View.VISIBLE);
	}

	public void showCity() {
			layout_city.setVisibility(View.GONE);
			layout_city_search.setVisibility(View.VISIBLE);
			citydragLayout.setType(intentType);
			citydragLayout.setStartName(address_name);
			citydragLayout.setIsSn(isInCity);
			citydragLayout.setIsStart(isStart);
			citydragLayout.setCurrentCity(tv_city.getText().toString());

			citydragLayout.setaddTextChangedListener(et_city, iv_city_delete);
			setEditTextCityFocusable();

		if(!citydragLayout.isOpen()){
			citydragLayout.open();
		}

	}

	public void hideCity() {
			layout_city.setVisibility(View.VISIBLE);
			layout_city_search.setVisibility(View.GONE);
			setEditTextSearchFocusable();

		if(citydragLayout.isOpen()){
			citydragLayout.close();
		}

	}
	/**
	 * 设置城市搜索为焦点
	 */
	public void setEditTextCityFocusable(){
		et_edit.setText("");
		et_edit.setFocusable(false);
		et_city.setFocusable(true);
		et_city.setFocusableInTouchMode(true);
		et_city.requestFocus();
		et_city.requestFocusFromTouch();
		//    	showInput();

	}
	/**
	 * 设置搜索框为焦点
	 */
	public void setEditTextSearchFocusable(){
		et_city.setText("");
		et_city.setFocusable(false);
		et_edit.setFocusable(true);
		et_edit.setFocusableInTouchMode(true);
		et_edit.requestFocus();
		et_edit.requestFocusFromTouch();
		showInput();
	}
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {

			// if (layout_search.getVisibility() == View.VISIBLE) {
			// if (intentType == AddressMsg.ADDRESS_START)
			// hideEditText();
			// else
			// onfinish();
			// } else {
			// onfinish();
			// }
			onfinish();
			return true;

		}
		return false;
	}

	public void notifyDataSetChanged(BaseAdapter adapter) {
		onisShowNodata(adapter,false);
		tv_loading.setVisibility(View.GONE);
	}

	public void onisShowNodata(BaseAdapter adapter,boolean isRecommend) {
		if (adapter == mMyAdapter_search) {
			type = TYPE_SEARCH;
			mMyAdapter_search.setRecommend(isRecommend);
			listview.setAdapter(mMyAdapter_search);
			adapter.notifyDataSetChanged();
		} else if (adapter == mMyAdapter_geocoder) {
			type = TYPE_GEOCODER;
			mMyAdapter_geocoder.setRecommend(isRecommend);
			listview.setAdapter(mMyAdapter_geocoder);
			adapter.notifyDataSetChanged();
		} else if (adapter == mMyAdapter_collect) {
			type = TYPE_COLLECT;
			mMyAdapter_collect.setRecommend(isRecommend);
			listview.setAdapter(mMyAdapter_collect);
			adapter.notifyDataSetChanged();
		}
	}
	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_SELETE_CITY:
				String s = (String) msg.obj;
				String city = s.split(split)[0];
				try {
					is_detail = s.split(split)[1];
				} catch (Exception e) {
				}
				onIsSearchDetail(is_detail, city);
				break;
			}
		}
	};

	/**
	 * 判断左上角有没有城市，true,没城市
	 */
	public boolean isNoCity() {
		boolean isnocity = false;
		if (tv_city.getText().toString().equals("null")
				|| tv_city.getText().toString().equals("")
				|| tv_city.getText().toString()
				.equals(getString(R.string.default_city))) {
			isnocity = true;
		}
		return isnocity;
	}

	/**
	 * 设置中心点位置
	 */
	public void setCenterPoint(double lat, double lng, final int zoom) {
		LatLng cenpt = new LatLng(lat, lng);
		MapStatus mMapStatus = new MapStatus.Builder().target(cenpt).build();
		MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory
				.newMapStatus(mMapStatus);
		mBaiduMap.animateMapStatus(mMapStatusUpdate);
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				MapStatusUpdate u = MapStatusUpdateFactory.zoomTo(zoom);
				mBaiduMap.animateMapStatus(u);
			}
		}, 500);

	}

	@Override
	public void onDragViewStatus(boolean isOpen) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onClickCity(String city, String is_detail) {
		setEditTextSearchFocusable();
		et_city.setText("");
		if(is_detail==null&&isInCity){
			is_detail = Value.CITY_NODETAIL;
		}
		if (city != null && is_detail != null) {
			hideCity();
			this.is_detail=is_detail;
			onIsSearchDetail(is_detail, city);
		}
	}
	@Override
	public void onNotifyData(DATA_STATUS data_status, DATA_TYPE data_type, int status,Object object) {
		  switch(data_type){
	        case LINE:
	    		if (IsDataFail.isDataFail(data_status)) {
	                return;
	            }
				setCityList();
	        	break;
	     }
	}

	/**
	 * 监控城市选择
	 * */
	public class cityTextWatcher implements TextWatcher {
		public String old="";

		@Override
		public void afterTextChanged(Editable arg0) {
			// TODO Auto-generated method stub

		}

		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			old=arg0+"";

		}

		@Override
		public void onTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			if(!old.equals(arg0+"")){
				readAllDB_address();
			}
		}

	}

	/**
	 * 设置默认城市
	 */
	public void setDefaultCity(boolean isStart){
		if(defaultcity==null||defaultcity.equals("")){
			if(isStart||isInCity)
			tv_city.setText(isInCity?mApplication.loctionSnCity:mApplication.loctionCity);
		}else{
			tv_city.setText(defaultcity);
		}

	}
	public void setCityList(){
		if(isStart){
			ToCity2.setStartCityList(isInCity);
		}else{
			ToCity2.setEndCityList(this,main.getStartCity(isInCity),isInCity);
		}
	}
}
